package com.example.server;

import com.example.server.util.StringUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import org.omg.IOP.Encoding;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 2
 */
public class ClientController {
    private static boolean thFlag = true;
    private boolean flag = true;
    private Socket socket;
    private PrintWriter out;
    @FXML
    private TextArea textFile;
    @FXML
    private TextField tfip;
    @FXML
    private TextField tfprot;
    @FXML
    private TextArea textArea;

    @FXML
    public void onStartClick() {
        if (flag) {
            new ReceiveThread(textArea, tfip.getText(), tfprot.getText());
        } else {
            textArea.appendText("INFO: 已连接\n");
        }
    }

    @FXML
    public void onSendClick() {
        if (out != null) {
            String text = textFile.getText();
            out.println(text.replaceAll("\\s*", ""));
            textArea.appendText("Client: \n" + text + "\n");
        } else {
            textArea.appendText("ERROR: 没有客户端接入\n");
        }
    }

    final byte BEGIN_BYTE = 0x02;//报文开始标记
    final byte END_BYTE = 0x03;//报文结束标记
    final String ITEM_DELIMITER = String.valueOf(((char) 15));//域分隔符

    /**
     * 发送喷码印字
     */
    @FXML
    public void onSendMarkSignClick() {
        if (out != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(new String(new byte[]{BEGIN_BYTE}));//开始符

            sb.append("ORDER").append(ITEM_DELIMITER).append("17585816");//工单号改为明细ID
            sb.append(ITEM_DELIMITER).append("NUM").append(ITEM_DELIMITER).append(100);//长度
            sb.append(ITEM_DELIMITER).append("T1").append(ITEM_DELIMITER).append("远东电缆有限公司");//公司名称
            sb.append(ITEM_DELIMITER).append("T2").append(ITEM_DELIMITER).append("远东电缆");//商标
            sb.append(ITEM_DELIMITER).append("T3").append(ITEM_DELIMITER).append("ZR-YJV");//型号
            sb.append(ITEM_DELIMITER).append("T4").append(ITEM_DELIMITER).append("0.6/1kV");//电压
            sb.append(ITEM_DELIMITER).append("T5").append(ITEM_DELIMITER).append("3×70+2×35");//规格
            sb.append(ITEM_DELIMITER).append("T6").append(ITEM_DELIMITER).append("(苏)XK06-001-00038");//认证标识
            sb.append(ITEM_DELIMITER).append("T7").append(ITEM_DELIMITER).append(new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis()));//生产日期
            sb.append(ITEM_DELIMITER).append("T8").append(ITEM_DELIMITER).append("Z1222053011");//质保编号
            sb.append(ITEM_DELIMITER).append("T9").append(ITEM_DELIMITER).append("201289985296970959335239955052446");//特殊要求

            sb.append(new String(new byte[]{END_BYTE}));//结束符
            String text = sb.toString();
            out.println(text);
            textArea.appendText("Client: \n" + text + "\n");
        } else {
            textArea.appendText("ERROR: 没有客户端接入\n");
        }
    }

    public void onFormatClick() {
        String text = textFile.getText();
        textFile.setText(StringUtils.formatJson(text));
    }

    class ReceiveThread extends Thread {
        private final TextArea textArea;
        private final String ip;
        private final int port;

        public ReceiveThread(TextArea textArea, String ip, String port) {
            this.ip = ip;
            this.port = Integer.parseInt(port);
            this.textArea = textArea;
            start();
        }

        @Override
        public void run() {
            try {
                socket = new Socket(ip, port);
            } catch (IOException e) {
                textArea.appendText("ERROR: 未找到服务\n");
            }
            try(InputStream in = socket.getInputStream()){
                textArea.appendText("INFO: 已连接服务\n");
                new SendThread(socket);
                String charSetType = "GB2312";
                byte[] data = new byte[1024 * 4];
                int len = 0;
                ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
                Integer dataLen = 0;
                while ((len = in.read(data)) != -1) {
                    bytesOut.write(data, 0, len);
                    dataLen = bytesOut.toByteArray().length;

                    if(bytesOut.toString(charSetType).endsWith(new String(new byte[]{END_BYTE}))){
                        break;
                    }
                }

                System.out.println("返回数据：" + bytesOut.toString(charSetType));

                String rs = bytesOut.toString(charSetType);

                Integer stlength = (new String(new byte[]{BEGIN_BYTE})).length();
                Integer etlength = (new String(new byte[]{END_BYTE})).length();
                if(rs.contains("RECEIVE")) {
                    String[] textArray= rs.split(ITEM_DELIMITER);
                    String workCode = textArray[0].substring(stlength,(textArray[0].length()));
                    System.out.println("工单号为："+workCode);
                    String resultCode = textArray[2];
                    resultCode = resultCode.substring(0,(resultCode.length()-etlength));

                    switch(resultCode){
                        case "0"://信息正确
                            System.out.println("信息正确");
                            break;
                        case "1"://信息格式错误
                            System.out.println("信息格式错误");
                            break;
                        case "2"://打标米数错误
                            System.out.println("打标米数错误");
                            break;
                        case "3"://与打标文件不对应
                            System.out.println("与打标文件不对应");
                            break;
                    }
                }else if(rs.contains("ENABLE")) {
                    System.out.println("喷码机取消喷码");

                }else if(rs.contains("ORDER")) {
                    String[] processArray = rs.split("NUM");
                    String[] numArray = processArray[1].split(ITEM_DELIMITER);
                    String num = numArray[1];
                    System.out.println(num+"米");
                }else if(rs.contains("END")) {
                    if(rs.contains(ITEM_DELIMITER)) {
                        String[] rsArray = rs.split(ITEM_DELIMITER);
                        String code = rsArray[0].substring(stlength,rsArray[0].length());
                        System.out.println("工单号为："+code);
                        System.out.println("工单号为："+code+"喷码完成");
                    }else {
                        System.out.println("整体喷码结束");
                    }
                }
//            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
//                textArea.appendText("INFO: 已连接服务\n");
//                new SendThread(socket);
//                flag = false;
//                List<Character> list = new ArrayList<>();
//                while (true) {
//                    char[] bufferBytes = new char[1024 * 8];
//                    int length = in.read(bufferBytes);
//                    String s1 = String.valueOf(list.toArray());
//                    if(null != s1){
//                        Byte aByte1 = Byte.valueOf(s1);
//                    }
//                }

                   /* if (length > 0)
                    {
                        for (int i = 0; i < length; i++)
                        {
                            //开始标记
                            if (bufferBytes[i] == BEGIN_BYTE)
                            {
                                list.clear();
                            }
                            //结束标记
                            else if (bufferBytes[i] == END_BYTE)
                            {
                                String s = String.valueOf(list.toArray());
                                Byte aByte = Byte.valueOf(s);
                                textArea.appendText("Client: \n" + s + "\n");
                                if (s.toUpperCase() == "END")
                                {
                                    in.close();
                                    return;
                                }
                                else if (s.toUpperCase().endsWith("END"))
                                {

                                }
                            }
                            else
                            {
                                list.add(bufferBytes[i]);
                            }
                        }
                    }*/
            } catch (IOException e) {
                textArea.appendText("ERROR: 未找到服务\n");
            }
        }
    }

    class SendThread extends Thread {
        private final Socket socket;

        public SendThread(Socket socket) {
            this.socket = socket;
            start();
        }

        @Override
        public void run() {
            try {
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

